package com.flycms.framework.manager.factory;

import java.util.TimerTask;

import com.flycms.common.constant.Constants;
import com.flycms.common.utils.LogUtils;
import com.flycms.common.utils.ServletUtils;
import com.flycms.common.utils.StrUtils;
import com.flycms.common.utils.ip.IpUtils;
import com.flycms.common.utils.spring.SpringUtils;
import com.flycms.modules.monitor.domain.FlyLogininfor;
import com.flycms.modules.monitor.domain.OperLog;
import com.flycms.modules.monitor.service.IFlyLogininforService;
import com.flycms.modules.monitor.service.IFlyOperLogService;
import com.flycms.modules.data.domain.dto.IpAddressDTO;
import com.flycms.modules.data.service.IIpAddressService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 异步工厂（产生任务用）
 * 
 * @author kaifei sun
 */
@Component
public class AsyncFactory
{
    private static final Logger fly_admin_logger = LoggerFactory.getLogger("sys-user");

    @Autowired
    private IIpAddressService ipAddressService;

    private static AsyncFactory asyncFactory;

    @PostConstruct
    public void init() {
        asyncFactory = this;
        asyncFactory.ipAddressService = this.ipAddressService;
    }
    /**
     * 记录登陆信息
     * 
     * @param username 用户名
     * @param status 状态
     * @param message 消息
     * @param args 列表
     * @return 任务task
     */
    public static TimerTask recordLogininfor(final String username, final String status, final String message,
            final Object... args)
    {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        return new TimerTask()
        {
            @Override
            public void run()
            {
                StringBuffer sb = new StringBuffer();
                if(StrUtils.isboolIp(ip)){
                    IpAddressDTO address=asyncFactory.ipAddressService.findSearchIpAddress(ip);
                    if(address != null){

                        if(!StrUtils.isEmpty(address.getProvince())){
                            sb.append(address.getProvince());
                        }
                        if(!StrUtils.isEmpty(address.getCity())){
                            sb.append(","+address.getCity());
                        }
                        if(!StrUtils.isEmpty(address.getCounty())){
                            sb.append(","+address.getCounty());
                        }
                    }
                }
                String address = sb.toString();
                StringBuilder s = new StringBuilder();
                s.append(LogUtils.getBlock(ip));
                s.append(address);
                s.append(LogUtils.getBlock(username));
                s.append(LogUtils.getBlock(status));
                s.append(LogUtils.getBlock(message));
                // 打印信息到日志
                fly_admin_logger.info(s.toString(), args);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                FlyLogininfor logininfor = new FlyLogininfor();
                logininfor.setUserName(username);
                logininfor.setIpaddr(ip);
                logininfor.setLoginLocation(address);
                logininfor.setBrowser(browser);
                logininfor.setOs(os);
                logininfor.setMsg(message);
                // 日志状态
                if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status))
                {
                    logininfor.setStatus(Constants.SUCCESS);
                }
                else if (Constants.LOGIN_FAIL.equals(status))
                {
                    logininfor.setStatus(Constants.FAIL);
                }
                // 插入数据
                SpringUtils.getBean(IFlyLogininforService.class).insertLogininfor(logininfor);
            }
        };
    }

    /**
     * 操作日志记录
     * 
     * @param operLog 操作日志信息
     * @return 任务task
     */
    public static TimerTask recordOper(final OperLog operLog)
    {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                // 远程查询操作地点
                StringBuffer sb = new StringBuffer();
                if(StrUtils.isboolIp(operLog.getOperIp())){
                    IpAddressDTO address=asyncFactory.ipAddressService.findSearchIpAddress(operLog.getOperIp());
                    if(address != null){
                        if(!StrUtils.isEmpty(address.getProvince())){
                            sb.append(address.getProvince());
                        }
                        if(!StrUtils.isEmpty(address.getCity())){
                            sb.append(","+address.getCity());
                        }
                        if(!StrUtils.isEmpty(address.getCounty())){
                            sb.append(","+address.getCounty());
                        }
                    }
                }
                operLog.setOperLocation(sb.toString());
                SpringUtils.getBean(IFlyOperLogService.class).insertOperlog(operLog);
            }
        };
    }
}
